/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package inventurserver;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

/**
 *
 * @author Streblow
 */
public class MainFrame extends javax.swing.JFrame {
    
    public String m_IPAddress;
    public Integer m_Port;
    public Long m_Hash;
    public String m_Filename;
    public Boolean m_Running;
    public Boolean m_StopRequested;
    public Integer m_Threads;
    public ServerSocket m_sSocket = null;
    public final CSVFile m_csvFile = new CSVFile();
    
    public javax.swing.JButton m_StartStopButton;
    public Boolean m_LogData;

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
        m_IPAddress = "127.0.0.1";
        m_Port = 55555;
        m_Hash = 0L;
        m_Filename = "Inventur.csv";
        m_Running = false;
        m_StopRequested = false;
        m_Threads = 0;
        try {
            for (NetworkInterface netinterface : Collections.list(NetworkInterface.getNetworkInterfaces()))
                for (InetAddress address : Collections.list(netinterface.getInetAddresses()))
                    if (address.getHostAddress().startsWith("192.168.")) {
                        m_IPAddress = address.getHostAddress();
                    }
        } catch (SocketException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        setTitle("InventurServer (" + m_IPAddress + ") - stopped");
        this.spnPort.requestFocus();
        writeLog("InventurServer \u00a9 2014 Lars Streblow");
        m_StartStopButton = this.btnStartStop;
        m_LogData = false;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblPort = new javax.swing.JLabel();
        spnPort = new javax.swing.JSpinner();
        lblHash = new javax.swing.JLabel();
        txtHash = new javax.swing.JTextField();
        lblFile = new javax.swing.JLabel();
        txtFile = new javax.swing.JTextField();
        btnStartStop = new javax.swing.JButton();
        lblLog = new javax.swing.JLabel();
        scpLog = new javax.swing.JScrollPane();
        lstLog = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("InventurServer () - stopped");

        lblPort.setLabelFor(spnPort);
        lblPort.setText("Port:");

        spnPort.setModel(new javax.swing.SpinnerNumberModel(55555, 49152, 65535, 1));
        spnPort.setName(""); // NOI18N
        spnPort.setValue(55555);

        lblHash.setLabelFor(txtHash);
        lblHash.setText("Hashwert:");

        txtHash.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtHash.setText("0");

        lblFile.setLabelFor(txtFile);
        lblFile.setText("Dateiname (.csv):");

        txtFile.setText("Inventur");

        btnStartStop.setText("Start");
        btnStartStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartStopActionPerformed(evt);
            }
        });

        lblLog.setText("Log:");

        lstLog.setModel(new DefaultListModel());
        scpLog.setViewportView(lstLog);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scpLog)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(lblFile, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE)
                                    .addComponent(lblPort, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(lblHash, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(btnStartStop)
                                    .addComponent(txtHash, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(spnPort, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtFile, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(lblLog))
                        .addGap(0, 103, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPort)
                    .addComponent(spnPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblHash)
                    .addComponent(txtHash, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblFile)
                    .addComponent(txtFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnStartStop)
                .addGap(18, 18, 18)
                .addComponent(lblLog)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scpLog)
                .addContainerGap())
        );

        lblFile.getAccessibleContext().setAccessibleName("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnStartStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartStopActionPerformed
        if (m_Running) {
            if (m_Threads == 0) {
                //stop Listener-Thread
                m_StopRequested = true;
                try {
                    Socket cSocket = new Socket("127.0.0.1", m_Port);
                    cSocket.close();
                } catch (IOException ex) {
                    //###add some handling here to signal server can't be stopped
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                m_Running = false;
                setTitle("InventurServer (" + m_IPAddress + ") - stopped");
                this.btnStartStop.setText("Start");
                this.spnPort.setEnabled(true);
                this.txtHash.setEnabled(true);
                this.txtFile.setEnabled(true);
                writeLog("Server stopped listening on port " + m_Port);
                try {
                    m_csvFile.close();
                } catch (IOException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            try {
                m_Hash = Long.parseLong(this.txtHash.getText());
            } catch (NumberFormatException ex) {
                m_Hash = 0L;
                this.txtHash.setText("0");
                this.txtHash.requestFocus();
                return;
            }
            //start Listener-Thread
            m_Running = true;
            m_StopRequested = false;
            m_Port = Integer.parseInt(this.spnPort.getValue().toString());
            //###add some handling to avoid double extension .csv
            m_Filename = this.txtFile.getText() + ".csv";
            setTitle("InventurServer (" + m_IPAddress + ") - running");
            this.btnStartStop.setText("Stop");
            this.spnPort.setEnabled(false);
            this.txtHash.setEnabled(false);
            this.txtFile.setEnabled(false);
            writeLog("Server started listening on port " + m_Port);
            try {
                m_csvFile.open(m_Filename);
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
            (new Thread(new Listener(this))).start();
        }
    }//GEN-LAST:event_btnStartStopActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    
    public final synchronized void writeLog(String str) {
        DefaultListModel listmodel = (DefaultListModel)this.lstLog.getModel();
        listmodel.addElement(str);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnStartStop;
    private javax.swing.JLabel lblFile;
    private javax.swing.JLabel lblHash;
    private javax.swing.JLabel lblLog;
    private javax.swing.JLabel lblPort;
    private javax.swing.JList lstLog;
    private javax.swing.JScrollPane scpLog;
    private javax.swing.JSpinner spnPort;
    private javax.swing.JTextField txtFile;
    private javax.swing.JTextField txtHash;
    // End of variables declaration//GEN-END:variables

}
